package controller

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/errors/gcode"
	"github.com/gogf/gf/errors/gerror"
	"gitlab.local/DO-module/new-filemanage-module/src/constant"
	"gitlab.local/DO-module/new-filemanage-module/src/controller/errcode"
	"gitlab.local/DO-module/new-filemanage-module/src/core/fileoperate"
	"golang.org/x/sys/unix"

	"gitlab.local/DO-module/new-filemanage-module/src/core/middleware"
	"gitlab.local/DO-module/new-filemanage-module/src/service/file_recently"
	"gitlab.local/DO-module/new-filemanage-module/src/service/file_share"
	"gitlab.local/DO-module/new-filemanage-module/src/service/filesystem"
	"gitlab.local/DO-module/new-filemanage-module/src/service/folder"
	//"gitlab.local/TerraMaster/tos-modules/middleware"
	"gitlab.local/golibrary/resp"
	"gitlab.local/golibrary/utils"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
)

type FileNavController struct {
	fs      *filesystem.FileSystem
	folders *folder.Folder
}

func InitFileNavRouter(engine *gin.Engine,
	checker middleware.AuthChecker,
	fs *filesystem.FileSystem,
	folders *folder.Folder) *FileNavController {

	fn := FileNavController{}
	fn.fs = fs
	fn.folders = folders

	fileManage := engine.Group("/fileManage")
	{
		//文件分享
		fileManage.GET("/GetShareStatus", resp.WrapResp(fn.handleGetShareStatus))                      //获取分享文件可操作状态
		fileManage.GET("/GetShareFileData", resp.WrapResp(fn.handleGetShareFileData))                  //获取分享文件(夹)或分享文件夹下文件信息
		fileManage.GET("/DownloadShareFile", fn.handleDownloadShareFile)                               //下载分享文件
		fileManage.POST("/VerifySharePwd", resp.WrapResp(fn.handleVerifySharePwd))                     //验证分享文件密码
		fileManage.GET("/GetShareFolder", resp.WrapResp(fn.handleGetShareFolder))                      //获取分享上传的目录
		fileManage.POST("/ShareFolderCheckQuota", resp.WrapResp(fn.handleShareFolderCheckQuota))       //判断分享目录是否能容纳文件
		fileManage.POST("/UploadShareFile", resp.WrapResp(fn.handleUploadShareFile))                   //上传分享文件
		fileManage.POST("/IncreaseViewCount", resp.WrapResp(fn.handleIncreaseViewCount))               //增加浏览量,扣除可访问次数
		fileManage.GET("/ShareMultimediaPlay", fn.handleShareMultimediaPlay)                           //多媒体播放（用于分享功能）
		fileManage.POST("/AddShareLinkFileControl", resp.WrapResp(fn.handleAddShareLinkFileControl))   //添加分享链接中的分享文件(有权限控制)
		fileManage.DELETE("/DelShareLinkFileControl", resp.WrapResp(fn.handleDelShareLinkFileControl)) //删除分享链接中的分享文件(有权限控制)
	}

	fileManage = engine.Group("/fileManage", checker.LoginAuthed())
	{
		//导航栏
		fileManage.GET("/Nav", resp.WrapResp(fn.handleNav))
		fileManage.GET("/GetHomePath", resp.WrapResp(fn.handleGetHomePath))
		//文件分享
		fileManage.POST("/checkNFSSMBFolder", resp.WrapResp(fn.checkNFSSMBFolder))       //检查远程文件夹nfs smb是否有效
		fileManage.POST("/IsShare", resp.WrapResp(fn.handleIsShare))                     //判断是否有分享文件
		fileManage.GET("/GetShareList", resp.WrapResp(fn.handleGetShareList))            //获取分享列表
		fileManage.POST("/AddShareFile", resp.WrapResp(fn.handleAddShareFile))           //添加分享文件
		fileManage.DELETE("/DelShare", resp.WrapResp(fn.handleDelShare))                 //删除分享
		fileManage.GET("/GetShareMsg", resp.WrapResp(fn.handleGetShareMsg))              //获取单个分享信息
		fileManage.POST("/AddShareLinkFile", resp.WrapResp(fn.handleAddShareLinkFile))   //添加分享链接中的分享文件
		fileManage.DELETE("/DelShareLinkFile", resp.WrapResp(fn.handleDelShareLinkFile)) //删除分享链接中的分享文件
		fileManage.POST("/EditShare", resp.WrapResp(fn.handleEditShare))                 //编辑分享配置
		fileManage.POST("/SwitchCloseStatus", resp.WrapResp(fn.handleSwitchCloseStatus)) //切换分享关闭和开启状态
		fileManage.GET("/GetShareDataMsg", resp.WrapResp(fn.handleGetShareDataMsg))      //获取某个分享链接的文件信息
		fileManage.POST("/GetPathWriteAcl", resp.WrapResp(fn.handleGetPathWriteAcl))     //判断某个地址是否存在，并且判断地址是否有写入权限

		//收藏
		fileManage.GET("/collect/list", resp.WrapResp(fn.handleGetCollectList)) //获取收藏文件列表信息
		fileManage.POST("/AddCollect", resp.WrapResp(fn.handleAddCollect))      //添加收藏
		fileManage.DELETE("/DelCollect", resp.WrapResp(fn.handleDelCollect))    //删除收藏
		//桌面
		fileManage.POST("/CreateDesktopFolder", resp.WrapResp(fn.handleCreateDesktopFolder)) //创建桌面(文件、文件夹、快捷方式)
		fileManage.DELETE("/DeleteDesktopFile", resp.WrapResp(fn.handleDeleteDesktopFile))   //删除桌面文件(创建的文件、文件夹、快捷方式)
		//最近
		fileManage.POST("/SetRecentlyConf", resp.WrapResp(fn.handleSetRecentlyConf)) //设置最近配置信息
		fileManage.GET("/GetRecentlyConf", resp.WrapResp(fn.handleGetRecentlyConf))  //获取最近配置信息
		fileManage.GET("/GetRecentlyFile", resp.WrapResp(fn.handleGetRecentlyFile))  //获取最近文件
		fileManage.DELETE("/DelRecently", resp.WrapResp(fn.handleDelRecently))       //删除最近
		//保险箱
		fileManage.POST("/SetSafeBoxPwd", resp.WrapResp(fn.handleSetSafeBoxPwd))                  //设置保险箱密码
		fileManage.GET("/GetSafeBoxConf", resp.WrapResp(fn.handleGetSafeBoxConf))                 //保险箱配置
		fileManage.POST("/CloseSafeBox", resp.WrapResp(fn.handleCloseSafeBox))                    //关闭保险箱
		fileManage.POST("/OpenSafeBox", resp.WrapResp(fn.handleOpenSafeBox))                      //开启保险箱
		fileManage.GET("/SafeBoxList", resp.WrapResp(fn.handleGetSafeBoxList))                    //保险箱列表
		fileManage.POST("/SafeBoxToDir", resp.WrapResp(fn.handleSafeBoxToDir))                    //移出保险箱文件到目录
		fileManage.GET("/GetSafeBoxPath", resp.WrapResp(fn.handleGetSafeBoxPath))                 //获取保险箱path
		fileManage.GET("/GetSafeBoxFileSearch", resp.WrapResp(fn.handleGetSafeBoxFileSearch))     //保险箱搜索
		fileManage.POST("/ResetSafe", resp.WrapResp(fn.handleResetSafe))                          //保险箱重置
		fileManage.GET("/ResetVerificationImage", resp.WrapResp(fn.handleResetVerificationImage)) //重置保险箱图片

		fileManage.GET("/desktop/list", resp.WrapResp(fn.handleDesktopList)) //桌面
	}

	return &fn
}

// handleNav 导航栏(位置)
func (fn *FileNavController) handleNav(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.NavLocation(username)
}

// handleGetHomePath 获取家目录路径
func (fn *FileNavController) handleGetHomePath(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetHomePath(username)
}

// ------------------------------------文件分享--------------------------------------------
// HandleIsShare 判断用户是否有分享文件
func (fn *FileNavController) handleIsShare(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.IsShare(username, c.Query("tag")), nil
}

// handleGetShareList 获取分享列表
func (fn *FileNavController) handleGetShareList(c *gin.Context) (interface{}, error) {
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetShareList(username, c.Query("tag"), page, limit)
}

// handleGetShareFileData 获取分享文件(夹)或分享文件夹下文件信息
func (fn *FileNavController) handleGetShareFileData(c *gin.Context) (interface{}, error) {
	shareLink := c.Query("shareLink")
	if shareLink == "" {
		return nil, errors.New("parameter parsing failed")
	}
	return fn.fs.FileNav.GetShareFileData(shareLink, c.Query("pwd"), c.Query("path"), c.Request.Context())
}

// handleAddShareFile 添加分享文件
func (fn *FileNavController) handleAddShareFile(c *gin.Context) (interface{}, error) {
	var data file_share.ShareData
	//解析json
	if e := c.BindJSON(&data); e != nil {
		return nil, e
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.AddShareFile(username, data)
}

// handleDelShare 删除分享
func (fn *FileNavController) handleDelShare(c *gin.Context) (interface{}, error) {
	id := c.Query("id")
	atId, err := strconv.Atoi(id)
	if err != nil {
		return false, err
	}
	err = fn.fs.FileNav.DelShare(atId)
	return err == nil, err
}

// handleGetShareMsg 获取单个分享信息
func (fn *FileNavController) handleGetShareMsg(c *gin.Context) (interface{}, error) {
	atId, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		return nil, errors.New("id failed")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetShareMsg(username, atId)
}

// handleAddShareLinkFile 添加分享链接中的分享文件
func (fn *FileNavController) handleAddShareLinkFile(c *gin.Context) (interface{}, error) {
	var data struct {
		Id   int      `json:"id"`
		Path []string `json:"path"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.Id == 0 {
		return false, errors.New("id is empty")
	}
	if len(data.Path) == 0 {
		return false, errors.New("parameter error")
	}
	err := fn.fs.FileNav.AddShareLinkFile(data.Id, data.Path)
	return err == nil, err
}

// handleDelShareLinkFile 删除分享链接中的分享文件
func (fn *FileNavController) handleDelShareLinkFile(c *gin.Context) (interface{}, error) {
	var data struct {
		Id   int      `json:"id"`
		Path []string `json:"path"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.Id == 0 {
		return false, errors.New("id is empty")
	}
	if len(data.Path) == 0 {
		return false, errors.New("parameter error")
	}
	err := fn.fs.FileNav.DelShareLinkFile(data.Id, data.Path)
	return err == nil, err
}

// handleEditShare 编辑分享配置
func (fn *FileNavController) handleEditShare(c *gin.Context) (interface{}, error) {
	data := &file_share.EditShare{}
	if err := c.BindJSON(data); err != nil {
		return false, err
	}
	err := fn.fs.FileNav.EditShare(data)
	return err == nil, err
}

// handleDownloadShareFile 下载分享文件
func (fn *FileNavController) handleDownloadShareFile(c *gin.Context) {
	shareLink := c.Query("shareLink")
	src := c.QueryArray("src")
	if shareLink == "" || len(src) == 0 {
		c.String(http.StatusOK, "parameter Incomplete")
		return
	}
	fn.fs.FileNav.DownloadShareFile(c, shareLink, src, c.Query("pwd"))
}

// handleVerifySharePwd 验证分享文件密码
func (fn *FileNavController) handleVerifySharePwd(c *gin.Context) (interface{}, error) {
	shareLink := c.PostForm("shareLink")
	pwd := c.PostForm("pwd")
	if shareLink == "" {
		return nil, errors.New("parameter parsing failed")
	}
	return fn.fs.FileNav.VerifySharePwd(shareLink, pwd)
}

// handleGetShareStatus 获取分享文件可操作状态
func (fn *FileNavController) handleGetShareStatus(c *gin.Context) (interface{}, error) {
	shareLink := c.Query("shareLink")
	if shareLink == "" {
		return nil, errors.New("parameter parsing failed")
	}
	return fn.fs.FileNav.GetShareStatus(shareLink)
}

// handleUploadShareFile 分享文件上传（暂时没用到）
func (fn *FileNavController) handleUploadShareFile(c *gin.Context) (interface{}, error) {
	return fn.fs.FileNav.HandleUploadShareFile(c, fn.fs.FileFunc.FileUpload)
}

// handleSwitchCloseStatus 切换分享关闭和开启状态
func (fn *FileNavController) handleSwitchCloseStatus(c *gin.Context) (interface{}, error) {
	var data struct {
		Id     int  `json:"id"`
		Status bool `json:"status"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	err := fn.fs.FileNav.SwitchCloseStatus(data.Id, data.Status)
	return err == nil, err
}

// handleGetShareDataMsg 获取某个分享链接的文件信息
func (fn *FileNavController) handleGetShareDataMsg(c *gin.Context) (interface{}, error) {
	id, _ := strconv.Atoi(c.Query("id"))
	if id == 0 {
		return nil, errors.New("id error")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetShareDataMsg(id, username)
}

// handleGetPathWriteAcl 判断某个地址是否存在，并且判断地址是否有写入权限
func (fn *FileNavController) handleGetPathWriteAcl(c *gin.Context) (interface{}, error) {
	tmp := struct {
		Path string `json:"path"`
	}{}
	if c.ShouldBindJSON(&tmp) != nil && tmp.Path == "" {
		return false, gerror.NewCode(errcode.InvalidParam, tmp.Path)
	}

	_, err := os.Stat(tmp.Path)
	if os.IsNotExist(err) {
		return false, gerror.NewCode(errcode.PathDoesNotExist, tmp.Path)
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	if !fn.folders.Acl.IsWrite(tmp.Path, username) {
		return false, gerror.NewCode(errcode.PermissionDenied, tmp.Path)
	}

	return true, nil
}

// handleIncreaseViewCount 增加浏览量,扣除可访问次数
func (fn *FileNavController) handleIncreaseViewCount(c *gin.Context) (interface{}, error) {
	var data struct {
		ShareLink string `json:"share_link"`
		Pwd       string `json:"pwd"`
	}
	if err := c.BindJSON(&data); err != nil {
		return nil, err
	}
	if data.ShareLink == "" {
		return nil, errors.New("parameter error")
	}
	return fn.fs.FileNav.IncreaseViewCount(data.ShareLink, data.Pwd)
}

// handleShareMultimediaPlay 多媒体播放（用于分享功能）
func (fn *FileNavController) handleShareMultimediaPlay(c *gin.Context) {
	shareLink := c.Query("share_link")
	if shareLink == "" {
		c.String(http.StatusInternalServerError, "share_link is empty")
		return
	}
	path := c.Query("path")
	if path == "" {
		c.String(http.StatusInternalServerError, "path is empty")
		return
	}
	if err := fn.fs.FileNav.ShareMultimediaPlay(shareLink, c.Query("pwd"), path, c); err != nil {
		c.String(http.StatusInternalServerError, err.Error())
	}
}

// handleAddShareLinkFileControl 添加分享链接中的分享文件(有权限控制)
func (fn *FileNavController) handleAddShareLinkFileControl(c *gin.Context) (interface{}, error) {
	var data struct {
		ShareLink string   `json:"share_link"`
		Path      []string `json:"path"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.ShareLink == "" {
		return false, errors.New("share_link is empty")
	}
	if len(data.Path) == 0 {
		return false, errors.New("parameter error")
	}
	err := fn.fs.FileNav.AddShareLinkFileControl(data.ShareLink, data.Path)
	return err == nil, err
}

// handleDelShareLinkFileControl 删除分享链接中的分享文件(有权限控制)
func (fn *FileNavController) handleDelShareLinkFileControl(c *gin.Context) (interface{}, error) {
	var data struct {
		ShareLink string   `json:"share_link"`
		Path      []string `json:"path"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.ShareLink == "" {
		return false, errors.New("share_link is empty")
	}
	if len(data.Path) == 0 {
		return false, errors.New("parameter error")
	}
	err := fn.fs.FileNav.DelShareLinkFileControl(data.ShareLink, data.Path)
	return err == nil, err
}

// 判断分享目录是否能容纳文件
func (fn *FileNavController) handleShareFolderCheckQuota(c *gin.Context) (interface{}, error) {

	var checkQuota struct {
		Folder         string `json:"path"`
		UploadFileSize uint64 `json:"size"`
	}
	if err := c.ShouldBindJSON(&checkQuota); err != nil {
		return nil, err
	}

	// 外部分享上传的目录都是分享创建者家目录下,所以不用判断储存配额
	s, e := os.Stat(checkQuota.Folder)
	if e != nil {
		return 0, gerror.Wrap(e, "stat folder")
	}
	if !s.IsDir() {
		return 0, errors.New("dir is not a folder")
	}

	fs := &unix.Statfs_t{}
	if e = unix.Statfs(checkQuota.Folder, fs); e != nil {
		return 0, gerror.Wrap(e, "GetPathSize")
	}
	return fs.Bfree*uint64(fs.Bsize) > checkQuota.UploadFileSize, nil
}

// 获取分享上传的目录
func (fn *FileNavController) handleGetShareFolder(c *gin.Context) (interface{}, error) {

	shareLink := c.Query("shareLink")
	if shareLink == "" {
		return nil, errors.New("share link not found")
	}

	folderDir, err := fn.fs.FileNav.GetShareFolder(shareLink)
	shareFolder := struct {
		FolderName string `json:"folder_name"`
	}{
		FolderName: folderDir,
	}

	return shareFolder, err
}

//--------------------分享 end----------------------------------------------

/*---------------------------------收藏 start-----------------------------------------*/
// handleGetCollectList 获取收藏文件列表信息
func (fn *FileNavController) handleGetCollectList(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	return fn.fs.FileNav.GetCollectListFilter(c.Query("order") == "true", fileoperate.OrderRule(c.Query("rule")), username, page, limit), nil
}

// handleAddCollect 添加收藏
func (fn *FileNavController) handleAddCollect(c *gin.Context) (interface{}, error) {
	var data struct {
		Paths []string `json:"paths"`
	}
	//解析json
	if e := c.BindJSON(&data); e != nil {
		return false, e
	}
	if len(data.Paths) == 0 {
		return false, errors.New("paths empty")
	}
	uname, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	//切换执行用户
	if e := utils.SwitchUserRight(uname); e != nil {
		return false, e
	}
	e := fn.fs.FileNav.AddCollectFilter(uname, data.Paths)
	return e == nil, e
}

// handleDelCollect 删除收藏
func (fn *FileNavController) handleDelCollect(c *gin.Context) (interface{}, error) {
	paths := strings.Split(c.Query("paths"), ",")
	if len(paths) == 0 {
		return false, errors.New("paths is empty")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	e := fn.fs.FileNav.DelCollect(username, paths)
	return e == nil, e
}

/*---------------------------------收藏 end-----------------------------------------*/

// handleCreateDesktopFolder 创建桌面文件或文件夹
func (fn *FileNavController) handleCreateDesktopFolder(c *gin.Context) (interface{}, error) {
	var data struct {
		Names []string `json:"names"` //名称或路径
		Type  int8     `json:"type"`  //1:文件,2:文件夹,3:快捷方式
	}
	//解析json
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if len(data.Names) == 0 || data.Type == 0 {
		return false, errors.New("parameter parsing failed")
	}
	uname, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	for _, v := range data.Names {
		switch data.Type {
		case 1, 2:
			//校验文件名称合法性
			if regexp.MustCompile(constant.FolderNameRule).MatchString(v) {
				return false, fmt.Errorf("the filename contains an illegal string(%s)", constant.FolderNameRule)
			}
		default:
			if !fn.folders.Acl.IsRead(v, uname) {
				return false, gerror.NewCode(errcode.PermissionDenied, v)
			}
		}
	}

	_ = utils.SwitchUserRight(uname)

	err = fn.fs.FileNav.CreateDesktopFolder(data.Names, uname, data.Type)
	return err == nil, err
}

// handleDeleteDesktopFile 删除桌面文件（创建的文件、文件夹、快捷方式）
func (fn *FileNavController) handleDeleteDesktopFile(c *gin.Context) (interface{}, error) {
	fName := c.Query("f_name")
	if fName == "" {
		return false, errors.New("f_name is empty")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	err = fn.fs.FileNav.DeleteDesktopFile(fName, username)
	return err == nil, err
}

// handleSetRecentlyConf 设置最近配置信息
func (fn *FileNavController) handleSetRecentlyConf(c *gin.Context) (interface{}, error) {
	data := &file_recently.RecentlyConf{}
	if e := c.BindJSON(data); e != nil {
		return false, e
	}
	uname, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	//切换执行用户
	if e := utils.SwitchUserRight(uname); e != nil {
		return false, e
	}
	e := fn.fs.FileNav.SetRecentlyConf(uname, data)
	return e == nil, e
}

// handleGetRecentlyConf 获取最近配置信息
func (fn *FileNavController) handleGetRecentlyConf(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetRecentlyConf(username)
}

// handleGetRecentlyFile 获取最近文件
func (fn *FileNavController) handleGetRecentlyFile(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetRecentlyFileFilter(username)
}

// handleDelRecently 删除最近
func (fn *FileNavController) handleDelRecently(c *gin.Context) (interface{}, error) {
	path := c.QueryArray("paths")
	if len(path) == 0 {
		return false, errors.New("paths is empty")
	}
	err := fn.fs.FileNav.DelRecently(path)
	return err == nil, err
}

/*--------------------------------------保险箱 start------------------------------------------*/
// handleSetSafeBoxPwd 设置保险箱密码
func (fn *FileNavController) handleSetSafeBoxPwd(c *gin.Context) (interface{}, error) {
	var data struct {
		Password string `json:"pass_word"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.Password == "" {
		return false, errors.New("pass_word is empty")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	err = fn.fs.FileNav.SetSafeBoxPwd(username, data.Password)
	return err == nil, err
}

// handleGetSafeBoxConf 保险箱配置
func (fn *FileNavController) handleGetSafeBoxConf(c *gin.Context) (interface{}, error) {
	var data struct {
		Status     bool   `json:"status"`
		IsPassWord bool   `json:"is_pass_word"`
		Path       string `json:"path"`
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	a, b, path, err := fn.fs.FileNav.GetSafeBoxConf(username)
	data.Status = a
	data.IsPassWord = b
	data.Path = path
	return data, err
}

// handleCloseSafeBox 关闭保险箱
func (fn *FileNavController) handleCloseSafeBox(c *gin.Context) (interface{}, error) {
	var data struct {
		Force bool `json:"force"` //是否强制
	}
	if err := c.BindJSON(&data); err != nil {
		return 0, err
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.CloseSafeBox(username, data.Force)
}

// handleOpenSafeBox 开启保险箱
func (fn *FileNavController) handleOpenSafeBox(c *gin.Context) (interface{}, error) {
	var data struct {
		Password  string `json:"pass_word"`  //密码
		ImageCode string `json:"image_code"` //图片
		ImageId   string `json:"image_id"`   //图片id
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if data.Password == "" {
		return false, errors.New("pass_word is empty")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.OpenSafeBox(username, data.Password, data.ImageCode, data.ImageId)
}

// handleSafeBoxToDir 移出保险箱文件到目录
func (fn *FileNavController) handleSafeBoxToDir(c *gin.Context) (interface{}, error) {
	var data struct {
		Paths  []string `json:"paths"`
		OutDir string   `json:"out_dir"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	if len(data.Paths) == 0 {
		return false, errors.New("paths is empty")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.SafeBoxToDir(username, data.Paths, data.OutDir)
}

// handleGetSafeBoxPath 获取保险箱path
func (fn *FileNavController) handleGetSafeBoxPath(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetSafeBoxPath(username), nil
}

// handleGetSafeBoxFileSearch 保险箱搜索
func (fn *FileNavController) handleGetSafeBoxFileSearch(c *gin.Context) (interface{}, error) {
	fileName := c.Query("file_name")
	if fileName == "" {
		return nil, errors.New("file_name is empty")
	}
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	if limit == 0 {
		return nil, errors.New("a limit of zero is meaningless")
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetSafeBoxFileSearch(fileName, username, page, limit)
}

// handleGetSafeBoxList 保险箱列表
func (fn *FileNavController) handleGetSafeBoxList(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))

	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.GetSafeBoxList(username, page, limit)
}

// handleResetSafe 重置保险箱
func (fn *FileNavController) handleResetSafe(c *gin.Context) (interface{}, error) {
	var data struct {
		UserPassword string `json:"user_pass_word"`
	}
	if err := c.BindJSON(&data); err != nil {
		return false, err
	}
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.ResetSafe(username, data.UserPassword)
}

// handleResetImage 重置保险箱验证图片
func (fn *FileNavController) handleResetVerificationImage(*gin.Context) (interface{}, error) {
	return fn.fs.FileNav.ResetVerificationCode(), nil
}

/*--------------------------------------保险箱 end------------------------------------------*/

func (fn *FileNavController) checkNFSSMBFolder(c *gin.Context) (interface{}, error) {
	var ReqParam struct {
		FileType string `json:"fileType"`
		Path     string `json:"path"`
		Username string `json:"username"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&ReqParam); err != nil {
		return false, gerror.NewCode(gcode.New(34, err.Error(), "invalid param"))
	}
	if err := fn.folders.CheckNFSSMBFolder(ReqParam.FileType, ReqParam.Path, ReqParam.Username, ReqParam.Password); err != nil {
		return false, err
	}

	return true, nil
}

// handleDesktopList 桌面
func (fn *FileNavController) handleDesktopList(c *gin.Context) (interface{}, error) {
	username, err := middleware.GetUserName(c)
	if err != nil {
		return nil, err
	}
	return fn.fs.FileNav.DesktopList(username), nil
}
